package com.infoauto.opc.gateway.opc.factory;

import com.infoauto.opc.gateway.model.gtm4.*;
import com.infoauto.opc.gateway.opc.model.DeviceLogNode;
import com.infoauto.opc.gateway.opc.model.SubscribeNode;
import com.infoauto.opc.gateway.opc.utils.HttpClientUtil;
import com.infoauto.opc.gateway.opc.utils.SpringContextUtils;
import com.infoauto.opc.gateway.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.infoauto.opc.gateway.opc.utils.DataTypeConversionUtils.DataTypeConversionToString;

/**
 * 设备日志工厂类
 **/
public class DeviceLogFactory {
    @Autowired
    private SpringContextUtils springContextUtils;
    // <summary>
    /// Manager实例
    /// </summary>
    private static DeviceLogFactory _manager;
    /// <summary>
    /// 锁定实例
    /// </summary>
    private static Object oClassLock = new Object();

    /// <summary>
    /// 得到该实例
    /// </summary>
    /// <returns></returns>
    public static DeviceLogFactory Instance() {
        synchronized (oClassLock) //加锁只生成一个实例
        {
            if (_manager == null) {
                _manager = new DeviceLogFactory();
            }
        }
        return _manager;
    }

    /// <summary>
    /// 私有的构造函数,防止从外部实例化
    /// </summary>
    private DeviceLogFactory() {
        mapDeviceLog = Collections.synchronizedMap(new HashMap<>());
    }

    /// <summary>
    /// 得到该实例
    /// </summary>
    public static DeviceLogFactory This() {
        return Instance();
    }

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private Map<Integer, DeviceLogNode> mapDeviceLog;

//    /**
//     * 添加点到对应接口中
//     */
//    public void addDeviceLog(DeviceLogNode node) {
//        if (node != null) {
//            mapDeviceLog.put(node.getLogNodeID().getNodeID(), node);
//        }
//    }
    /**
     * 日志数据处理
     * */
    public void doLogHandle(SubscribeNode sn){
        if(sn!=null && sn.getGroupName()!=null) {
            switch (sn.getGroupName()) {
                case "equipmentAbnormal":
                    this.saveEquipmentAbnormal(sn);
                    break;
                case "controlSignal":
                    this.saveControlSignal(sn);
                    break;
                case "monthlyOutput":
                    this.saveMonthlyOutput(sn);
                    break;
                case "shift":
                    this.saveShift(sn);
                    break;
                case "eps":
                    this.saveEps(sn);
                    break;
                default:
                    break;
            }
        }
    }


    //班次基础数据
    private boolean saveEps(SubscribeNode sn) {
        boolean flag = false;
        try {
            //localhost:7088/epsCfg/writeByRfid
            Map<String, String> fromData = new HashMap<>();
            fromData.put("rfid",sn.getNodeValue().getValue().toString());
            String station  = sn.getNodeName().split("_")[0];
            fromData.put("station",station);
            HttpClientUtil.doPostRequest("http://20.67.113.227:7088/epsCfg/writeByRfid",fromData);
            flag = true;
        } catch (Exception ex) {
            logger.error("saveEps method error = {}", ex.getMessage());
        }
        return flag;
    }
    //班次基础数据
    private boolean saveShift(SubscribeNode sn) {
        boolean flag = false;
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            ShiftService shiftService = springContextUtils.getBean(ShiftService.class);
            //根据生产时间查询当前班次
            Shift shift = shiftService.selectByProductionTime(formatter.format(new Date()));
            if(shift!=null){
                shift.setShift(Integer.parseInt(DataTypeConversionToString(sn.getNodeValue())));
                shift.setModifyDateTime(new Date());
                shiftService.update(shift);
            }else {
                Shift shift1 = new Shift();
                shift1.setId(UUID.randomUUID().toString().replaceAll("-", ""));//主键
                shift1.setProductionTime(formatter.format(new Date()));//生产时间
                shift1.setShift(Integer.parseInt(DataTypeConversionToString(sn.getNodeValue())));//班次
                shift1.setCreateUser("SA");
                shift1.setCreateDateTime(new Date());
                shift1.setModifyUser("SA");
                shift1.setModifyDateTime(new Date());
                shiftService.insert(shift1);
            }
            flag = true;
        } catch (Exception ex) {
            logger.error("saveShift method error = {}", ex.getMessage());
        }
        return flag;
    }

    //月度统计数据
    private boolean saveMonthlyOutput(SubscribeNode sn) {
        boolean flag = false;
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            MonthlyOutputService monthlyOutputService = springContextUtils.getBean(MonthlyOutputService.class);
            MonthlyProjectService monthlyProjectService = springContextUtils.getBean(MonthlyProjectService.class);
            //根据plc地址查询控制器信号所属工程
            MonthlyProject monthlyProject = monthlyProjectService.selectByPlcAdrr(sn.getNodeName());
            ShiftService shiftService = springContextUtils.getBean(ShiftService.class);
            Shift shift = shiftService.selectByProductionTime(formatter.format(new Date()));//查询当前班次
            if(monthlyProject!=null) {
                /**
                 * 每天每班每个项目只会有一条数据生成，
                 */
                if (shift != null) {
                    MonthlyOutput monthlyOutput = monthlyOutputService.selectPlcAdrrAndProductionTime(sn.getNodeName(), shift.getShift());
                    if (monthlyOutput != null) {
                        monthlyOutput.setProduction(Integer.parseInt(DataTypeConversionToString(sn.getNodeValue())));//更新产量
                        monthlyOutput.setModifyDateTime(new Date());//更新更新时间
                        monthlyOutputService.update(monthlyOutput);
                    } else {
                        MonthlyOutput mo = new MonthlyOutput();
                        mo.setId(UUID.randomUUID().toString().replaceAll("-", ""));//主键
                        mo.setGroupName(monthlyProject.getGroupName());//分组
                        mo.setProjectName(monthlyProject.getProjectName());//项目名称
                        mo.setPlcAdrr(sn.getNodeName());//plc地址
                        mo.setUnit(monthlyProject.getUnit());//单位
                        mo.setProductionTime(formatter.format(new Date()));//生产时间
                        mo.setProduction(Integer.parseInt(DataTypeConversionToString(sn.getNodeValue())));//产量
                        mo.setShift(shift.getShift());
                        mo.setCreateDateTime(new Date());//创建时间
                        mo.setCreateUser("SA");//创建人
                        mo.setModifyDateTime(new Date());//修改时间
                        mo.setModifyUser("SA");//修改人
                        monthlyOutputService.insert(mo);
                    }

                }
            }
            flag = true;
        } catch (Exception ex) {
            logger.error("saveMonthlyOutput method error = {}", ex.getMessage());
        }
        return flag;
    }
    //控制信号列表数据采集
    private boolean saveControlSignal(SubscribeNode sn) {
        boolean flag = false;
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            ControlSignalService controlSignalService = springContextUtils.getBean(ControlSignalService.class);
            ControlSignalProjectService controlSignalProjectService = springContextUtils.getBean(ControlSignalProjectService.class);
            //根据plc地址查询控制器信号所属工程
            ControlSignalProject controlSignalProject = controlSignalProjectService.selectByplcAdrr(sn.getNodeName());
            if(controlSignalProject!=null){
                ControlSignal controlSignal = new ControlSignal();
                controlSignal.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                controlSignal.setStationName(controlSignalProject.getStationName());//工程名
                controlSignal.setProjectName(controlSignalProject.getProjectName());//项目名
                controlSignal.setChangeTime(new Date());//变化时间
                controlSignal.setProductionTime(formatter.format(new Date()));//生产时间
                if (DataTypeConversionToString(sn.getNodeValue()).equals("true")) {
                    controlSignal.setStates(0);//ON
                }else{
                    controlSignal.setStates(1);//OFF
                }
                controlSignal.setCreateDateTime(new Date());//创建时间
                controlSignal.setCreateUser("SA");//创建人
                controlSignal.setModifyDateTime(new Date());//修改时间
                controlSignal.setModifyUser("SA");//修改人
                controlSignalService.insert(controlSignal);
            }
            flag = true;
        } catch (Exception ex) {
            logger.error("saveControlSignal method error = {}", ex.getMessage());
        }
        return flag;
    }
    //设备异常数据采集
    private boolean saveEquipmentAbnormal(SubscribeNode sn) {
        boolean flag = false;
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            EquipmentAbnormalService equipmentAbnormalService = springContextUtils.getBean(EquipmentAbnormalService.class);
            EquipmentService equipmentService = springContextUtils.getBean(EquipmentService.class);
            Equipment equipment = equipmentService.selectByplcAddr(sn.getNodeName());
            EquipmentAbnormal equipmentAbnormal = new EquipmentAbnormal();
            if(equipment!=null) {
                List<EquipmentAbnormal> list = equipmentAbnormalService.selectPlcAdrrAndRemoveTime(equipment.getPlcAdrr());
                equipmentAbnormal.setEquipmentCompany(equipment.getEquipmentCompany());
                equipmentAbnormal.setEquipmentName(equipment.getEquipmentName());
                if (DataTypeConversionToString(sn.getNodeValue()).equals("true")) {
                    if (list.size() == 0) {
                        equipmentAbnormal.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                        equipmentAbnormal.setEquipmentState(equipment.getAlarmLevel());//报警状态
                        equipmentAbnormal.setPlcAddress(equipment.getPlcAdrr());//plc地址
                        equipmentAbnormal.setProductionTime(formatter.format(new Date()));//当天生产时间
                        equipmentAbnormal.setStartTime(new Date());//异常发生时间
                        equipmentAbnormal.setCreateUser("SA");
                        equipmentAbnormal.setCreateDateTime(new Date());
                        equipmentAbnormal.setModifyUser("SA");
                        equipmentAbnormal.setModifyDateTime(new Date());
                        equipmentAbnormalService.insert(equipmentAbnormal);
                    }
                } else {
                    if (list != null && list.size() > 0) {
                        for (EquipmentAbnormal ea : list) {
                            ea.setModifyDateTime(new Date());
                            ea.setEquipmentState(2);//0-故障；信号恢复正常 1-异常；2-正常；
                            ea.setRemoveTime(new Date());//异常解除时间
                            equipmentAbnormalService.update(ea);
                        }
                    }
                }
            }
            flag = true;
        } catch (Exception ex) {
            logger.error("saveEquipmentAbnormal method error = {}", ex.getMessage());
        }
        return flag;
    }
}
